package top.ligongzi.hrm.feign.interceptor;

import top.ligongzi.hrm.util.HttpUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

//Fiegn拦截器
@Component //交给Spirng管理
@Slf4j
public class TempOAuth2FeignRequestInterceptor implements RequestInterceptor {

    //客户端模式授权地址
    private static final  String CLIENT_MODEL_AUTH_URL =
            "http://localhost:4020/oauth/token?client_id=%s&client_secret=%s&grant_type=client_credentials";
    private static  final String AUTHORIZATION = "Authorization";

    //底层ribbon发送http请求所需要模版
    @Override
    public void apply(RequestTemplate requestTemplate) {

        //如果请求头中本来就有，就不要获取

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null) {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)
                    requestAttributes;

            HttpServletRequest request = servletRequestAttributes.getRequest();
            String token = request.getHeader(AUTHORIZATION);
            if (StringUtils.hasLength(token))
                return;
        }
        //获取Token
        Map<String, String> result = HttpUtil.sendPost(String.format(CLIENT_MODEL_AUTH_URL, "temp", "1"));//替换占位服务%s
        if (result == null || StringUtils.isEmpty(result.get("access_token")))
        {
            log.error("Get token error!##########");
        }else{
            String token = "Bearer "+ result.get("access_token");
            //从设置值
            requestTemplate.header(AUTHORIZATION,token);
        }
    }
}